package com.util;

import com.enums.ServiceExceptionEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class CommonFunctionUtil {

    public static ServiceExceptionEnum getServiceError(String code)
    {
        for (ServiceExceptionEnum errorEnum : ServiceExceptionEnum.values()) {
            if (Objects.equals(errorEnum.getCode(), code)) {
                return errorEnum;
            }
        }
        return null;
    }

    /**
     * 获取客户端ip地址
     * @param request 请求参数
     * @return String
     */
    public static String getIpAddress(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getRemoteAddr();
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

    public static String formatServiceErrorMsg(ServiceExceptionEnum serviceExceptionEnum){
        return "【" + serviceExceptionEnum.getCode() + "】:"+ serviceExceptionEnum.getMsg();
    }

    public static String formatServiceErrorMsg(String errCode, String errMsg){
        return "【" +errCode + "】:"+errMsg;
    }

    public static String formatServiceErrorMsg(ServiceExceptionEnum serviceExceptionEnum, String... params){
        return "【" + serviceExceptionEnum.getCode() + "】:"+ serviceExceptionEnum.getFormattedMsg(params);
    }

}
